<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
      <el-breadcrumb-item to="/home/product/spumanage"
        >商品管理</el-breadcrumb-item
      >
      <el-breadcrumb-item to="/home/product/albummanage"
        >相册管理</el-breadcrumb-item
      >
      <el-breadcrumb-item>图片管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-divider></el-divider>

    <el-steps :active="2" simple style="margin-top: 20px">
      <el-step title="类目选择" icon="el-icon-files"></el-step>
      <el-step title="添加属性" icon="el-icon-s-operation"></el-step>
      <el-step title="添加图片" icon="el-icon-picture-outline"></el-step>
      <el-step title="添加详情" icon="el-icon-notebook-2"></el-step>
    </el-steps>

    <div class="box">
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <h3 style="line-height: 32px">
              <i class="el-icon-edit"></i> &nbsp; 图片管理
            </h3>
          </div>
        </el-col>
        <el-col :span="16" style="text-align: right">
          <div class="grid-content bg-purple">
            <el-button
              size="small"
              type="primary"
              :disabled="albumCreated"
              icon="el-icon-circle-plus-outline"
              @click="addAlbumDialogVisible = true"
              >新建相册</el-button
            >
            <el-upload
              multiple
              style="display: inline-block; margin: 0px 10px"
              :action="`${BASEURL.UPLOAD_BASEURL}/upload/picture/single`"
              name="file"
              :on-success="handleSuccess"
              :auto-upload="true"
              :show-file-list="false"
            >
              <el-button
                size="small"
                type="primary"
                :disabled="!albumCreated"
                icon="el-icon-circle-plus-outline"
                >上传图片</el-button
              >
            </el-upload>
            <el-button
              size="small"
              type="primary"
              icon="el-icon-circle-plus-outline"
              >批量选择</el-button
            >
          </div>
        </el-col>
      </el-row>

      <div class="divider"></div>

      <div v-if="albumCreated">
        <div class="namerow">
          {{ this.ruleForm.albumInfo.name }}
        </div>
        <el-row class="descrow">
          {{ this.ruleForm.albumInfo.description }}
        </el-row>
        <el-row class="bzrow">
          <p>1. 单图图片尺寸为：300*300，文件大小不得超过300k)</p>
          <p>2. 商城前端最多展示10张图片</p>
        </el-row>
      </div>
    </div>

    <div class="box">
      <div v-if="albumCreated && pictures.length != 0">
        <photo-pic-item
          v-for="(item, i) in pictures"
          :key="i"
          :currentPic="item"
          :index="i + 1"
          :selected="item.selected"
          @coverChanged="handleCoverChanged"
          @picSelected="handlePicSelected"
          @picCancelSelected="handlePicCancelSelected"
        >
        </photo-pic-item>

        <div class="pagination">
          <el-pagination
            background
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            layout="total, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
      <div v-else>
        <el-empty description="没有任何图片"></el-empty>
      </div>
      <div class="divider"></div>
      <el-button @click="$router.go(-1)">上一步，添加属性</el-button>
      <el-button type="primary" @click="nextStep()">下一步，添加详情</el-button>
    </div>

    <!-- 新增相册 -->
    <el-dialog
      title="新建相册"
      :visible.sync="addAlbumDialogVisible"
      :modal-append-to-body="false"
    >
      <el-form :model="addForm">
        <el-form-item label="相册名称" label-width="120px">
          <el-input v-model="addForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="相册简介" label-width="120px">
          <el-input v-model="addForm.description" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序序号" label-width="120px">
          <el-input v-model="addForm.sort" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addAttrDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddForm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import photoPicItem from "@/components/PhotoPicItem.vue";
import LocalStorage from "@/common/StorageUtils.js";
export default {
  components: {
    photoPicItem,
  },
  data() {
    return {
      albumCreated: false, // 标识相册是否已经创建
      addAlbumDialogVisible: false, // 标识是否显示新建相册对话框
      addForm: {}, // 定义新建相册表单对象
      ruleForm: {}, // 定义新建SPU完成的表单数据
      pictures: [], // 定义当前相册中包含的所有图片
      currentPage: 1, // 当前页
      total: 0, // 总页数
      pageSize: 100, // 每页条目数

      cuser: {},

      input: "",
      value: "",
      options: [
        {
          value: "enable",
          label: "启用",
        },
        {
          value: "disable",
          label: "禁用",
        },
      ],
    };
  },
  methods: {
    nextStep() {
      // 验证是否选择了 spu需要显示的几张 picutures
      if (
        this.ruleForm.pictures == undefined ||
        this.ruleForm.pictures.length == 0
      ) {
        this.$message.error("必须选择至少一张的商品预览图片！");
      } else {
        this.ruleForm.pictures = this.ruleForm.pictures.toString();
        // 重新存入LocalStorage
        LocalStorage.save(LocalStorage.KEY_ADD_SPU, this.ruleForm);
        this.$router.push("/home/product/addspu/4");
      }
    },

    /** 当图片被取消选中时 */
    handlePicCancelSelected(picture) {
      console.log("取消选中", picture);
      for (let i = 0; i < this.ruleForm.pictures.length; i++) {
        if (this.ruleForm.pictures[i] == picture.url) {
          this.ruleForm.pictures.splice(i, 1);
          break;
        }
      }
    },

    /** 当图片被选中时 */
    handlePicSelected(picture) {
      console.log("选中", picture);
      // 向ruleForm.pictures中新增图片路径
      if (this.ruleForm.pictures == undefined) {
        this.ruleForm.pictures = [];
      }
      this.ruleForm.pictures.push(picture.url);
    },

    /** 处理更新封面后的业务 */
    handleCoverChanged() {
      this.loadAlbumPictures();
    },

    /** 选择图片确定时，将图片存入FormData */
    handleSuccess(res) {
      // 上传成功后，将该图片添加到相册
      console.log("上传成功，并将图片绑定到相册：", res);
      // 完善图片对象，新增数据，将图片绑定到相册
      let params = res.data;
      params.albumId = this.ruleForm.albumId;
      params.description = "";
      this.picturesApi.add(params).then((addRes) => {
        console.log("新增图片数据到相册", addRes);
        if (addRes.data.state == 200) {
          this.loadAlbumPictures();
        } else {
          this.$alert(res.data.message, "提示");
        }
      });
    },

    /** 处理更新页码后的业务 */
    handleCurrentChange(val) {
      console.log(`即将加载选中页: 第${val}页`);
      this.currentPage = val;
      this.loadAlbumPictures();
    },

    handleAvatarSuccess(res, file) {
      this.cuser.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    /** 提交新建相册 */
    submitAddForm() {
      this.albumApi.add(this.addForm).then((res) => {
        console.log("新建相册：", res);
        if (res.data.state == 200) {
          // 获取新建的相册ID,
          this.ruleForm.albumId = res.data.data.id;
          this.ruleForm.albumInfo = this.addForm;
          // 重新存入LocalStorage
          LocalStorage.save(LocalStorage.KEY_ADD_SPU, this.ruleForm);

          // 新建相册成功
          this.$message({
            showClose: true,
            message: "创建相册成功",
            type: "success",
          });
          this.addAlbumDialogVisible = false;
          this.albumCreated = true;
        } else {
          this.$alert(res.data.message, "提示");
        }
      });
    },

    /** 加载当前相册图片列表 */
    loadAlbumPictures() {
      let albumId = this.ruleForm.albumId;
      let page = this.currentPage;
      let pageSize = this.pageSize;
      this.picturesApi
        .queryByAlbumId({ albumId, page, pageSize })
        .then((res) => {
          console.log("加载当前图片列表", res)
          this.pictures = res.data.data.list;
          this.total = res.data.data.total;
        });
    },
  },

  /** 页面挂在完毕后执行 */
  mounted() {
    // 读取LocalStorage，加载缓存数据
    this.ruleForm = LocalStorage.get(LocalStorage.KEY_ADD_SPU);
    if (this.ruleForm.albumId) {
      // 已经创建了相册
      this.albumCreated = true;
      // 加载相册内容
      this.loadAlbumPictures();
    }
  },
};
</script>
<style scoped>
.namerow {
  font-weight: bold;
  font-size: 1.1em;
  color: #a33;
  margin-bottom: 20px;
}
.descrow {
  margin-bottom: 20px;
  color: #888;
}
.bzrow {
  columns: #666;
  font-size: 0.9em;
}
</style>
